import flask
from flask import request, Flask, render_template, jsonify, make_response
import logging, json
import hashlib, requests
import random, logging, os, time
from flask_cors import CORS, cross_origin
from db.defineDB import ownSqlDb

# 将一次性初始化内容放在该部分，作为全局变量
from app.envs.mc import MControl
mcu = MControl('niuneng')
odb = ownSqlDb()

from app.envs import log
# 
logger = logging.getLogger('debug')

def createApp():

    # 模版文件设定
    tpath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'templates'))
    # 创建app
    app = Flask(__name__, template_folder=tpath)
    # 跨域问题
    CORS(app, resources={r"/*": {"origins": "*"}})
    cors_origins = []

    # 微信认证
    @app.route("/WechatCertifi", methods=["POST", 'GET'])
    @cross_origin(origins=cors_origins)
    def tfunc():
        if request.method == 'GET':
            logger.info('收到get消息'.center(30, '-'))
            # 校验微信服务器行为
            try:
                data = eval(str(request.get_data(), encoding='utf-8'))
            except:
                data = request.args

            signature = data.get('signature')
            timestamp = data.get('timestamp')
            nonce = data.get('nonce')
            echostr = data.get('echostr')

            #该处的token为服务器后台配置的字符串
            token = 'niuneng2020'

            list = [token, timestamp, nonce]
            list.sort()
            list2 = ''.join(list)
            sha1 = hashlib.sha1()
            sha1.update(list2.encode('utf-8'))
            hashcode = sha1.hexdigest()

            if hashcode == signature:
                logger.info(' 返回信息 ' + echostr)
                return echostr
            else:
                logger.info('返回空字符串')
                return ''


        elif request.method == 'POST':
            logger.info('收到post消息'.center(30, '+'))
            webData = str(request.get_data(), encoding='utf-8')
            print(webData)
            import receive, reply
            recMsg = receive.parse_xml(webData)

            if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
                toUser = recMsg.FromUserName
                fromUser = recMsg.ToUserName
                content = '稍后反馈给您'
                replyMsg = reply.TextMsg(toUser, fromUser, content)
                replyData = replyMsg.send()
                logger.info('返回消息 ' + replyData)
                return replyData
            else:
                return 'success'

    # 生成微信密钥
    @app.route("/genSign", methods=["POST", 'GET'])
    @cross_origin(origins=cors_origins)
    def genSign():
        # 获取到前端参数
        from urllib.parse import unquote
        #print(str(request.body, encoding="utf-8"))
        p = unquote(str(request.get_data(), encoding="utf-8"))
        logger.info('收到请求参数'  + str(p))
        url = json.loads(p).get('data')
        # 生成签名所需字段
        params = {
            "noncestr":"randonstring",
            "jsapi_ticket": mcu.getJsTicket(),
            "timestamp":str(int(time.time())),
            "url": url
        }
        # 根据字段生成签名
        string = 'jsapi_ticket={jsapi_ticket}&noncestr={noncestr}&timestamp={timestamp}&url={url}'.format(**params)
        logger.info(string)
        sha1 = hashlib.sha1()
        sha1.update(string.encode('utf-8'))
        signature = sha1.hexdigest()
        # 组装返回结果
        from app.envs.data import info
        result = dict()
        result['appId'] = info.get('appid')
        result['timestamp'] = params.get('timestamp')
        result['nonceStr'] = params.get('noncestr')
        result['signature'] = signature
        return jsonify(result)


    # 获取设备信息
    @app.route("/getAvaliableToken", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def getAvaliableToken():
        return jsonify({'token':mcu.get_token()})

    #微信认证文件
    @app.route('/MP_verify_kmF36dNgoXbgfSvY.txt')
    @cross_origin(origins=cors_origins)
    def today():
        base_dir = os.path.dirname(__file__)
        resp = make_response(open(os.path.join(base_dir,'envs','MP_verify_kmF36dNgoXbgfSvY.txt')).read())
        resp.headers["Content-type"]="text/plain;charset=UTF-8"
        return resp

    # 扫一扫
    @app.route("/scan.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def scan():
        return render_template('scan.html')

    # 注册页面
    @app.route("/register.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def register():
        return render_template('register.html')

    # 注册扫码
    @app.route("/remainder.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def remainder():
        return render_template('remainder.html')

    # 操作页面
    @app.route("/operate.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def operate():
        return render_template('operate.html')

    # 注册扫码
    @app.route("/toOperate.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def toOpstatus():
        logger.info(request.url)
        return render_template('toOperate.html')

    # 注册扫码
    @app.route("/toCerti.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def toCerstatus():
        logger.info(request.url)
        return render_template('toCerti.html')

    # 注册扫码
    @app.route("/closedoor.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def closeStatus():
        return render_template('closedoor.html')

    # 注册扫码
    @app.route("/opendoor.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def openstatus():
        return render_template('opendoor.html')

    # 注册扫码
    @app.route("/pause.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def pausestatus():
        return render_template('pause.html')

    # 注册扫码
    @app.route("/toRegister.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def registarStatus():
        return render_template('toRegister.html')

    # 注册扫码
    @app.route("/scan2register.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def scan2register():
        return render_template('scan2register.html')

    # 用户注册
    @app.route("/userRegister", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def reg():
        #from app.users.util import usrRegister
        params = request.get_data()
        print('params', params)
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        # mock数据
        '''
        result = {
            'errcode': 0,
            'errmsg' : ''
        }'''
        #result = odb.register(dict_data.get('code'), dict_data.get('deviceid'))
        from app.backend.utils import usrRegister
        result = usrRegister(dict_data)
        # 设备小区绑定

        #result = usrRegister(dict_data)
        return jsonify(result)

    # changeLog: 直连的1v1关系，不再需要用户权限校验
    # 用户权限验证
    # @app.route("/userCheck", methods=['POST'])
    # @cross_origin(origins=cors_origins)
    # def cerCheck():
    #     from app.users.util import usrCerCheck
    #     params = request.get_data()
    #     dict_data = eval(str(params, encoding='utf-8'))
    #     #result, openid = usrCerCheck(dict_data)
    #     result, openid = odb.usrCheck(dict_data)
    #     logger.info(result)
        
    #     # 推送信息给用户
    #     from app.envs.reply import ReplyMsg
    #     from app.envs.urls import sendText
    #     if json.loads(result).get('errmsg') == 'no authority':
    #         ReplyMsg['touser'] = openid
    #         ReplyMsg['text']['content'] = '请点击扫码注册先进行认证'
    #         #replyData = json.dumps(ReplyMsg)
    #         logger.info(str(ReplyMsg))
    #         # 构造headers
    #         headers = {'Content-Type': 'application/json;charset=UTF-8'}
    #         v = requests.post(sendText.format(**{'token': mcu.get_token()}), headers=headers, data=ReplyMsg)
    #         logger.info(v.text)

    #     return jsonify(result)

    # 获取设备信息
    @app.route("/getDeviceInfo", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def getDeviceInfo():
        from app.devices.util import getDeviceInfo
        params = request.get_data()
        print(' getDeviceInfo ', params)
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        #result = getDeviceInfo(dict_data)
        #result = odb.getUserDevice(dict_data.get('code'))
        from app.backend.utils import getDeviceAndCommu
        result = getDeviceAndCommu(dict_data)
        print('get deviceinfo result is ', result)

        # 没有成功获取用户名下设备时，推送信息给用户
        if result.get('errcode') != 0:
            from app.envs.reply import ReplyMsg
            from app.envs.urls import sendText
            from tools.utils import code2openid
            ReplyMsg['touser'] = code2openid(dict_data.get('code'))
            ReplyMsg['text']['content'] = '请点击扫码注册先进行认证'
            #replyData = json.dumps(ReplyMsg)
            logger.info(str(ReplyMsg))
            # 构造headers
            headers = {'Content-Type': 'application/json;charset=UTF-8'}
            v = requests.post(sendText.format(**{'token': mcu.get_token()}), headers=headers, data=ReplyMsg)
            logger.info(v.text)

        return jsonify(result)

    '''
    # 获取社区信息
    @app.route("/getCommunityInfo", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def getCommunityInfo():
        from app.devices.util import getCommunityInfo
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        result = getCommunityInfo(dict_data)
        return jsonify(result)'''

    # 打开
    @app.route("/openDoor", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def openDoor():
        from app.devices.util import openDoor
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        result = openDoor(dict_data)
        return jsonify(result)

    # 关闭
    @app.route("/closeDoor", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def closeDoor():
        from app.devices.util import closeDoor
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        result = closeDoor(dict_data)
        return jsonify(result)

    # 暂停
    @app.route("/stopCmd", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def stopCmd():
        from app.devices.util import pauseCmd
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        print(dict_data)
        result = pauseCmd(dict_data)
        return jsonify(result)

    # 更新token
    @app.route("/updateToken", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def updateToken():
        mcu.update_token()
        result = {'errcode':0, 'errmsg':'ok'}
        return jsonify(result)
        

    # 预约设备
    @app.route("/subDevice", methods=['POST'])
    @cross_origin(origins=cors_origins)
    def subDevice():
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        logger.info('发生预约行为')
        from app.backend.utils import SetSub
        result = SetSub(dict_data)
        return jsonify(result)

    # 预约设备状态
    @app.route("/toOrderdevice.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def toSubDevice():
        return render_template('toOrderdevice.html')   


    # 预约设备界面
    @app.route("/orderdevice.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def orderdevice():
        return render_template('orderdevice.html')

    
    # 获取用户名下设备
    @app.route("/getUserDevice", methods=['GET', 'POST'])
    @cross_origin(origins=cors_origins)
    def getUserDevice():
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        #result = odb.getUserDevice(dict_data.get('userId'))
        from app.backend.utils import getUserDevice
        result = getUserDevice(dict_data)
        return jsonify(result)

    '''
    # 查询预约状态
    @app.route("/getSubStatus", methods=['GET', 'POST'])
    @cross_origin(origins=cors_origins)
    def getSubStatus():
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        result = odb.getSubStatus(dict_data.get('deviceid'))
        return jsonify(result) 
    '''


    # 预约历史记录
    @app.route("/checkhistory.html", methods=['GET'])
    @cross_origin(origins=cors_origins)
    def chistory():
        return render_template('checkhistory.html')

    # 获取预约历史记录
    @app.route("/getHistory", methods=['GET', 'POST'])
    @cross_origin(origins=cors_origins)
    def getHistory():
        params = request.get_data()
        dict_data = eval(str(params, encoding='utf-8'))
        logger.debug('获取预约历史参数 ' + str(dict_data))
        from app.backend.utils import getHistory
        #result = odb.getHistory(dict_data.get('userid'))
        result = getHistory(dict_data)
        return jsonify(result) 



    return app

